'use strict';

const BaseController = require('../../core/base_controller');
const xlsx = require('xlsx');
const path = require('path');
const uuid = require('uuid');
const {redis_set_dict_list} = require("../../../utils/init");
class DictionaryDetailController extends BaseController {
  async index() {
    const { ctx } = this;
    const { parent_id } = ctx.query;
    const where = {};
    if (parent_id) {
      where.parent_id = parent_id;
    }

    const list = await ctx.model.DictionaryDetail.findAll({
      where,
      order: [['sort', 'ASC']]
    });

    this.success(list);
  }


  async getDictDetailList() {
    const { ctx } = this;
    const { key:dict_key } = ctx.params;
    if (!dict_key) {
       ctx.throw(400,'缺少key值')
    }
    const item = await ctx.model.Dictionary.findOne({
      where:{dict_key}
    })
    if(!item) {
      ctx.throw(500,'未查到该字典')
    }
    const list = await ctx.model.DictionaryDetail.findAll({
      where:{
        parent_id:item.id
      },
      order: [['sort', 'ASC']]
    });

    this.success(list);
  }
  async getDictDetailLists() {
    const { ctx } = this;
    const { key:dict_key } = ctx.params;
    if (!dict_key) {
       ctx.throw(400,'缺少key值')
    }
    let obj = {}
    const dict_keys = dict_key.split(',')
    const data = await ctx.service.cache.get('dict_list')
    for(let item of dict_keys){
      obj[item] = data[item]
    }
    this.success(obj);
  }
  async create() {
    const { ctx } = this;
    const rules = {
      parent_id: { type: 'integer', required: true },
      dict_key: { type: 'string', required: true },
      dict_value: { type: 'string', required: true },
      sort: { type: 'integer', required: false },
      icon: { type: 'string', required: false },
      description: { type: 'string', required: false },
    };

    try {
      ctx.validate(rules);
    } catch (err) {
      ctx.throw(400, '参数错误');
    }

    const { parent_id } = ctx.request.body;
    const parent = await ctx.model.Dictionary.findByPk(parent_id);
    if (!parent) {
      ctx.throw(404, '父级字典不存在');
    }
    ctx.request.body.id = uuid.v4().replaceAll('-','')
    const detail = await ctx.model.DictionaryDetail.create(ctx.request.body);
    redis_set_dict_list(ctx.app)
    this.success(detail);
  }

  async update() {
    const { ctx } = this;
    const detail = await ctx.model.DictionaryDetail.findByPk(ctx.params.id);

    if (!detail) {
      ctx.throw(404, '字典详情不存在');
    }

    await detail.update(ctx.request.body);
    redis_set_dict_list(ctx.app)
    this.success(detail);
  }

  async destroy() {
    const { ctx } = this;
    const detail = await ctx.model.DictionaryDetail.findByPk(ctx.params.id);

    if (!detail) {
      ctx.throw(404, '字典详情不存在');
    }

    await detail.destroy();
    redis_set_dict_list(ctx.app)
    this.success(null, '删除成功');
  }

  async import() {
    const { ctx } = this;
    const { parent_id } = ctx.request.body;

    // 验证父级字典是否存在
    const parent = await ctx.model.Dictionary.findByPk(parent_id);
    if (!parent) {
      ctx.throw(404, '父级字典不存在');
    }

    // 获取上传的文件
    const file = ctx.request.files[0];
    if (!file) {
      ctx.throw(400, '请上传Excel文件');
    }

    // 添加调试信息
    console.log('文件信息:', {
      filename: file.filename,
      filepath: file.filepath,
      mime: file.mime,
      fieldname: file.fieldname,
      encoding: file.encoding,
    });

    // 验证文件类型
    const fileExt = path.extname(file.filename).toLowerCase();
    if (fileExt !== '.xlsx' && fileExt !== '.xls') {
      ctx.throw(400, '只支持.xlsx或.xls格式的Excel文件');
    }

    try {
      // 读取Excel文件
      const workbook = xlsx.readFile(file.filepath);
      const worksheet = workbook.Sheets[workbook.SheetNames[0]];
      const data = xlsx.utils.sheet_to_json(worksheet);

      // 验证数据格式
      if (data.length === 0) {
        ctx.throw(400, 'Excel文件内容为空');
      }

      // 验证必要的列是否存在
      const firstRow = data[0];
      if (!firstRow['键名'] || !firstRow['键值']) {
        ctx.throw(400, 'Excel文件格式错误，必须包含"键名"和"键值"列');
      }

      // 转换数据格式并批量创建
      const details = data.map((row, index) => ({
        parent_id,
        id:uuid.v4().replaceAll('-',''),
        dict_key:row['键值'] ,
        dict_value: row['键名'],
        sort: index, // 使用行号作为排序值
        description: row['描述'] || null,
        icon: row['图标'] || null
      }));

      await ctx.model.DictionaryDetail.bulkCreate(details);
      redis_set_dict_list(ctx.app)
      this.success(null, `成功导入${details.length}条数据`);
    } catch (error) {
      ctx.throw(500, '导入失败：' + error.message);
    } finally {
      // 清理临时文件
      await ctx.cleanupRequestFiles();
    }
  }

  // 更新排序
  async updateSort() {
    const { ctx } = this;
    const { items } = ctx.request.body;

    // 验证输入参数
    if (!Array.isArray(items)) {
      ctx.throw(400, '参数错误：items必须是数组');
    }

    if (items.length === 0) {
      ctx.throw(400, '参数错误：items不能为空数组');
    }

    // 验证每个item的格式
    items.forEach((item, index) => {
      if (!item.id || typeof item.sort !== 'number') {
        ctx.throw(400, `参数错误：第${index + 1}项数据格式不正确，需要包含id和sort字段`);
      }
    });

    try {
      // 使用循环逐个更新
      for (const item of items) {
        await ctx.model.DictionaryDetail.update(
          { sort: item.sort },
          { where: { id: item.id } }
        );
      }
      redis_set_dict_list(ctx.app)
      this.success(null, '排序更新成功');
    } catch (error) {
      ctx.throw(500, '更新排序失败：' + error.message);
    }
  }
}

module.exports = DictionaryDetailController;
